﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;

namespace Klinkby.PodCaster.Model
{
    [Serializable]
    class FeedCollection : LinkedList<IFeed>
    {
        public FeedCollection()
        { }
        protected FeedCollection(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {}
    }

    [Serializable]
    class Model : IModel
    {
        LinkedList<IFeed> _feeds = new FeedCollection();

        protected Model()
        { 
        }
        
        #region IModel Members

        public ICollection<IFeed> Feeds
        {
            get { return _feeds; }
        }
     
        public void RefreshFeeds()
        {             
            foreach (var feed in Feeds)
                feed.Refresh();                
        }

        public void Download()
        {
            Bits bits = null;
            foreach (var feed in Feeds)
            {
                var newPosts = from p in feed.Posts
                               where p.DownloadStatus == DownloadStatus.New
                               select p;
                if (newPosts.Count() > 0)
                {
                    if (bits == null)
                        bits = new Bits();
                    string localDir = feed.GetLocalDir();
                    if (!Directory.Exists(localDir))
                        Directory.CreateDirectory(localDir);
                    Guid jobId = bits.Download(newPosts.SelectMany(p => p.GetDownloadInfo(localDir)));
                    foreach (var post in newPosts)
                        post.MarkDownloading(jobId);
                }
            }
        }


        #endregion        


    }
}
